home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 684 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.0 KB  |  60 lines

  1. Path: news.th-darmstadt.de!news!enno
  2. From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: overloading stream output (<<) with a template...
  5. Date: 05 Jan 1996 20:15:33 GMT
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Distribution: world
  8. Message-ID: <ENNO.96Jan5211533@kitz.inferenzsysteme.informatik.th-darmstadt.de>
  9. References: <4chkcd$n8q@ns1.arlut.utexas.edu>
  10. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  11. In-reply-to: Lee Crites's message of 4 Jan 1996 22:29:33 GMT
  12.  
  13. In article <4chkcd$n8q@ns1.arlut.utexas.edu> Lee Crites <crites> writes:
  14.  
  15.    I have a template that is defined like this:
  16.  
  17.        template <int theType, int theLength, class T> class Stuff
  18.  
  19.    I would like to overload the << stream operator.  It works fine for the class
  20.    before I made it into a template, but I just can't seem to get the right
  21.    combination of things in the declarations of the ostream function.  Would some
  22.    kind soul out there please show me the proper format for the friend declaration
  23.    in the class and the actual ostream function declaration?
  24.  
  25. The following code is an example for a generic-friend function:
  26.  
  27. #include <iostream.h>
  28.  
  29. template <int theType, int theLength, class T> struct Stuff {
  30.   friend ostream& operator << (ostream&,const Stuff&);
  31. };
  32.  
  33. template<int theType, int theLength, class T> 
  34. inline ostream& operator << (ostream& o,const Stuff<theType,theLength,T>&) {
  35.   return o << "STUFF";
  36. }
  37.  
  38. int main()
  39. {
  40.   Stuff<1,2,char> s;
  41.   cout << s << endl;
  42. }
  43.  
  44. Many compilers still use the obsolete template-type unification which force
  45. an exact match for the arguments of templated function.
  46. These compilers will complain about this code, because the generic output
  47. function expects an 'ostream' reference as first argument but 'cout' is an
  48. instance of a subclass of 'ostream'.
  49. The wayout is quite simple --- just have a ostream-reference to cout, ie.
  50. change 'main' to:
  51.  
  52. int main()
  53. {
  54.   Stuff<1,2,char> s;
  55.   ostream& o=cout;
  56.   o << s << endl;
  57. }
  58.  
  59.     Enno
  60.